<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <canvas width="300" height="300"></canvas>
  <input type="number" min="3">
</body>
<script>
  const canvas = document.querySelector('canvas')
  const gl = canvas.getContext('webgl')


  const vertex = `
  attribute vec2 position;
  varying vec3 color;
  void main() {
    gl_PointSize = 1.0;
    color = vec3(0.0, 0.5 + position * 0.5);
    gl_Position = vec4(position, 0.0, 1.0);
  }
`;


  const fragment = `
  precision mediump float;
  varying vec3 color;
  void main()
  {
    gl_FragColor = vec4(color, 1.0);
  }    
`;

  // shader
  const vertexShader = gl.createShader(gl.VERTEX_SHADER);
  gl.shaderSource(vertexShader, vertex);
  gl.compileShader(vertexShader);


  const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  gl.shaderSource(fragmentShader, fragment);
  gl.compileShader(fragmentShader);

  // attach link
  const program = gl.createProgram()
  gl.attachShader(program, vertexShader)
  gl.attachShader(program, fragmentShader)
  gl.linkProgram(program)
  gl.useProgram(program)

  // const points = new Float32Array([
  //   -1, 1,
  //   -1, -1,
  //   1, -1,
  //   -1, 1,
  //   1, 1,
  //   1, -1
  // ])

  function getPoint (n) {
    const angle = Math.PI * 2 / n
    let x = 1
    let y = 0
    const temp = [1, 0]
    const cos = Math.cos(angle)
    const sin = Math.sin(angle)
    for (let i = 0; i < n - 1; i++) {
      const tx = x
      const ty = y
      x = cos * tx - sin * ty
      y = sin * tx + cos * ty
      // console.log(x, y, x * x + y * y)
      temp.push(x, y)
    }

    // console.log(temp)
    // return temp
    const res = []
    for (let i = 1; i < n - 1; i++) {
      res.push(...temp.slice(0, 2))
      res.push(...temp.slice(i * 2, i * 2 + 2))
      res.push(...temp.slice(i * 2 + 2, i * 2 + 4))
    }
    // console.log(res)
    return res
  }

  function render(n) {
  
    const points = new Float32Array(getPoint(n))
  
    // 创建，绑定，写入缓冲区
    // create and bind buffer
    // write data
    const bufferId = gl.createBuffer()
    gl.bindBuffer(gl.ARRAY_BUFFER, bufferId)
    gl.bufferData(gl.ARRAY_BUFFER, points, gl.STATIC_DRAW)
  
    // set attribute from buffer
    const vPosition = gl.getAttribLocation(program, 'position')
    gl.vertexAttribPointer(vPosition, 2, gl.FLOAT, false, 0, 0)
    gl.enableVertexAttribArray(vPosition)
  
  
    gl.clear(gl.COLOR_BUFFER_BIT)
    // draw
    gl.drawArrays(gl.TRIANGLES, 0, points.length / 2)
  }

  const input = document.querySelector('input')
  input.value = 3
  render(input.value)

  input.addEventListener('input', e => {
    // console.log(e)
    render(input.value)
  })

  // gl.drawArrays(gl.LINE_LOOP, 0, points.length / 2)
</script>

</html>